package StudyCode.summary.BufferAndChannel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class UsingAsynchronousFileChannelAndExecutorService {
	public static void main(String[] args) {
		final int THREADS = 5;
		ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);
		String encoding = System.getProperty("file.encoding");
		List<Future<ByteBuffer>> list = new ArrayList<>();
		int sheeps = 0;
		Path path = Paths.get("E:\\Copy", "1.txt");

		Set<StandardOpenOption> options = new HashSet<>();
		options.add(StandardOpenOption.READ);
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, options, taskExecutor)) {
			for (int i = 0; i < 50; i++) {
				Callable<ByteBuffer> worker = new Callable<ByteBuffer>() {
					@Override
					public ByteBuffer call() throws Exception {
						ByteBuffer buffer = ByteBuffer.allocateDirect(ThreadLocalRandom
								.current().nextInt(100, 200));
						asynchronousFileChannel.read(buffer, ThreadLocalRandom.current()
								.nextInt(0, 100));
						return buffer;
					}
				};
				Future<ByteBuffer> future = taskExecutor.submit(worker);
				list.add(future);
			}
			taskExecutor.shutdown();
			while (!taskExecutor.isTerminated()) {
				System.out.println((sheeps += 1));
			}
			for (Future<ByteBuffer> future : list) {
				ByteBuffer buffer = future.get();
				System.out.println("\n\n" + buffer);
				buffer.flip();
				System.out.print(Charset.forName(encoding).decode(buffer));
				buffer.clear();
			}
		} catch (Exception ex) {
			System.err.println(ex);
		}
	}
}
